// fast4j - Fast & Agile Service Tools for Java
// Copyright (C) 2007 Alexandre ROMAN
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

// $Id: ProfileInterceptor.java 36 2007-03-27 22:02:40Z alexandre.roman $

package service.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

/**
 * Profiler.
 * @author alexandre.roman
 */
public class ProfileInterceptor {
    private final Logger log = LoggerFactory.getLogger(getClass());
    
    /**
     * Logs messages when a method is called.
     * @param jp the method being called
     * @return result from method
     * @throws Throwable when the method raises an error
     */
    public Object profile(ProceedingJoinPoint jp) throws Throwable {
        final Signature sig = jp.getSignature();
        final String fullSig = '[' + sig.getDeclaringTypeName() + '.'
                + sig.getName() + ']';
        log.info("Entering {}", fullSig);
        
        final StopWatch stopWatch = new StopWatch();
        final Object ret;
        try {
            stopWatch.start();
            ret = jp.proceed();
            stopWatch.stop();
        } catch (Throwable e) {
            log.info("Throwing from " + fullSig, e);
            throw e;
        } finally {
            log.info("Leaving {} after {} ms", fullSig, stopWatch
                    .getTotalTimeMillis());
        }
        return ret;
    }
}
